package com.bzyd.verify.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class RequestUtil {

    /**
     * 获取IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 限制两次请求的时间间隔不能小于设定值
     * @param key 缓存key值
     * @param interval 时间间隔，单位秒
     * @param tip 提示信息
     */
    public static void rateLimit(String key, int interval, String tip) {
        String value = RedisUtil.get(key);
        //能获取到值表示未过期，即时间间隔小于设定值
        if (StringUtils.isNotEmpty(value)){
            throw new RuntimeException(tip);
        }else {
            RedisUtil.set(key,key,interval);
        }
    }

    /**
     * 限制单位时间内请求次数不能大于设定值
     *
     * @param key      key值
     * @param interval 时间间隔，单位分钟
     * @param num    次数
     * @param tip    提示信息
     * @return
     */
    public static void countLimit(String key, int interval, int num, String tip) {
        Long count = RedisUtil.incr(key);

        //count等于1表示刚创建
        if (count == 1){
            RedisUtil.setExp(key,interval*60);
        }

        if (count > num){
            //大于设定值
            throw new RuntimeException(tip);
        }
    }
}
